from rest_framework.viewsets import GenericViewSet, ModelViewSet
from rest_framework.decorators import action
# 导入日志对象
from utils.loggers import logger
from .serializers import UserRegisterSerializer, UserLoginSerializer, UserInfoSerializer, UserWxLoginSerializer, \
    MemrSerializer, UserIDInfoSerializer, UserAddressSerializer, ApplicationSerializer
from utils.common_response import APIResponse
from utils.common_mixins import ResponseMixin
from .models import User, Memorandum, UserDetail, Address, Application
from utils.common_pagination import CommonPageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
# 导入短信
from libs.tx_sms import get_code, send_sms
from django.core.cache import cache


class UserMobileView(GenericViewSet):
    # 局部禁用
    authentication_classes = []

    @action(methods=['get'], detail=False)
    def exist(self, request, *args, **kwargs):
        '''
        判断手机号是否存在
        '''
        mobile = request.query_params.get('mobile')
        if not mobile:
            raise Exception('请填写手机号')
        is_exist = True if User.objects.filter(phone=mobile) else False
        return APIResponse(results=is_exist)

    @action(['get'], detail=False)
    def sms(self, request, *args, **kwargs):
        # 获取电话
        mobile = request.query_params.get('mobile')
        # 生成验证码
        code = get_code()
        # 将验证码存放到缓存中供后续校验
        cache.set(f'sms_captcha_{mobile}', code, 300)
        # 提交celery异步任务
        send_sms.delay(mobile, code)
        return APIResponse(msg='短信已发送')


class UserLoginView(GenericViewSet):
    queryset = User.objects.all()
    # 局部禁用
    authentication_classes = []

    def get_serializer_class(self):
        if self.action == 'wx':
            return UserWxLoginSerializer
        else:
            return UserLoginSerializer

    # @action(methods=['POST'], detail=False)
    def create(self, request, *args, **kwargs):
        ser: UserLoginSerializer = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        return APIResponse(token=token, results=ser.data)

    @action(methods=['POST'], detail=False)
    def wx(self, request, *args, **kwargs):
        ser: UserWxLoginSerializer = self.get_serializer(data=request.data, context={
            'request': request,
            'school': request.data.get('school')
        })
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        return APIResponse(token=token, results=ser.data)


class UserRegisterView(GenericViewSet):
    serializer_class = UserRegisterSerializer
    # 局部禁用
    authentication_classes = []

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()
        return APIResponse()


class UserInfoView(ResponseMixin, ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserInfoSerializer
    # 分页类
    pagination_class = CommonPageNumberPagination
    # 过滤类
    filter_backends = [OrderingFilter, SearchFilter]
    # 排序字段
    ordering_fields = ['create_time', 'gender', 'is_superuser']
    # 搜索字段
    search_fields = ['username']

    @action(methods=['post'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()

    @action(methods=['put'], detail=True)
    def re_pass(self, request, *args, **kwargs):
        user = self.get_object()
        user.password = user.make_password('123456')
        user.save()
        return APIResponse()


class MemrView(ResponseMixin, ModelViewSet):
    queryset = Memorandum.objects.filter(is_delete=False, is_show=True)
    serializer_class = MemrSerializer

    def filter_queryset(self, queryset):
        school_id = self.request.query_params.get('school', None)

        if school_id is not None:
            queryset = queryset.filter(school_id=school_id)

        return queryset


class FileView(GenericViewSet):
    authentication_classes = []

    def create(self, request, *args, **kwargs):
        data = request.data
        print(data)
        return APIResponse(url='XXX')


class UserIDInfoView(ResponseMixin, ModelViewSet):
    queryset = UserDetail.objects.all()
    serializer_class = UserIDInfoSerializer


class AddressView(ResponseMixin, ModelViewSet):
    queryset = Address.objects.all()
    serializer_class = UserAddressSerializer

    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user']


class ApplicationView(ResponseMixin, ModelViewSet):
    queryset = Application.objects.filter(is_delete=False, is_show=True)
    serializer_class = ApplicationSerializer
    pagination_class = CommonPageNumberPagination
    # filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = ['applicant']
    # search_fields = ['state']

    def update(self, request, *args, **kwargs):
        instance = self.get_queryset().filter(pk=kwargs.get('pk')).first()
        if not instance:
            raise Exception('选择对象不存在')
        ser: ApplicationSerializer = self.get_serializer(instance=instance, data=request.data)
        ser.context['request'] = request
        ser.is_valid(raise_exception=True)
        ser.save()
        return APIResponse(results=ser.data)

    def get_queryset(self):
        query_set = super().get_queryset()
        if self.request.user.is_superuser:
            return query_set
        return query_set.filter(school=self.request.user.school)

    @action(methods=['post'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()
